package cn.itcast.flink.stream;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author lilulu
 * @date 2023-03-29 0:13
 */
public class StreamWordCount {
    public static void main(String[] args) throws Exception {
//        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
//        DataSource<String> stringDataSource = env.readTextFile("/datas/words.txt");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> source = env.socketTextStream("node1.itcast.cn", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> resultData = source.flatMap(
                new FlatMapFunction<String, String>() {
                    public void flatMap(String lines, Collector<String> collector) throws Exception {
                        String[] words = lines.trim().split("\\s+");
                        for (String word : words) {
                            collector.collect(word);
                        }
                    }
                }
        ).map(
                new MapFunction<String, Tuple2<String, Integer>>() {
                    public Tuple2<String, Integer> map(String word) throws Exception {
                        return Tuple2.of(word, 1);
                    }
                }
        ).keyBy(0).sum(1);
        resultData.print();
        env.execute("StreamWordCount");
    }
}
